/**
 * 
 */
package com.lanswon.qzsmk.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.HttpContants;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.model.PersonalTmp;

/**
 * @author sun
 *
 */
public class IMG {
	public static final String baseDir = "http://192.168.0.12:9999/qzsmk";
//	public static final String baseDir = "http://127.0.0.1:9999/qzsmk";
	



	/**
	 * 扫描附件保存目录
	 */
	private static final String in_single_enclosure_Dir_Physics =  baseDir+File.separator+"resource"+File.separator+"unEnclosures"+File.separator;

	/**
	 * 附件上传后移到指定物理路径下
	 */
//	private static final String out_single_enclosure_Dir_Physics = baseDir+File.separator+"resource"+File.separator+"Enclosuresed"+File.separator;

//	/**
//	 * 附件上传至工程下指定目录
//	 */
//	private static final String out_cert_Dir_Project = File.separator+"uploadImages/enclosures/";
//




	
	private static Logger logger = (Logger) LoggerFactory.getLogger(IMG.class);

	/**
	 * 
	 * @param req
	 * @param path 图片上传前所在路径
	 * @param outpath  输出工程目录
	 * @return 图片上传后的路径
	 */
	private static String readImage(String out, String path,String outpath) {

		String outPath =out+  outpath;// 输出目录

		logger.debug("相对路径--------"+outPath);
		
		File o = new File(outPath);
		if (!o.exists()) {
			o.mkdirs();
			logger.debug("新建目录[{}]",outPath);
		}
		File f = new File(path);
		byte[] data = null;
		InputStream input = null;
		ByteArrayOutputStream output = null;
		String p = "";
		try {
			
			input = HttpUtil.getInputStream(path);

			output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			p = importPicture(data, outPath, f.getName());
		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			try {
				if (output != null)
					output.close();
				if (input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
				 String msg1="IO流关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

			}
		}
		return p;
	}

	private static String importPicture(byte[] data, String outPath,
			String fileName) {
		File f = new File(outPath + File.separator + fileName);
		FileImageOutputStream imageOutput = null;
		try {
			imageOutput = new FileImageOutputStream(f);

			imageOutput.write(data, 0, data.length);
		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="IO流异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			try {
				if (imageOutput != null) {
					imageOutput.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				 String msg1="IO流关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

			}
		}

		return f.getPath();
	}
	
	
	

	/**
	 * 验证同一批次的 图片和个人信息
	 * @param list 该批次的个人信息
	 * @param applyBatchNo 批次号
	 * @return
	 * @throws ApplicationException
	 */
	public static  boolean validPhotos(List<PersonalTmp> list,String applyBatchNo,String root) throws ApplicationException{
		logger.debug("验证同一批次[{}]的 图片和个人信息",applyBatchNo);
			File ff = new File(root+PathContants.PROJECT_PATH_IMG+File.separator+applyBatchNo);
			if(!ff.exists()){
				ff.mkdirs();
			}
			File[] fff  = ff.listFiles();
			//如果图片的数量<员工的数量
			logger.debug("批次号【{}】,图片数量【{}】",applyBatchNo,fff.length);
			if(fff.length> 0){
				if(fff.length < list.size()){
					throw new ApplicationException(ErrorCode.FILE_IS_NULL, "photo number < peroanl number");
				}

				List<String> ll = new ArrayList<String>();//该批次下照片名称-证件号码  
				for(File file :fff){
					String f = file.getName();
					logger.debug("图片名称【{}】",f);
					ll.add(f.substring(0,f.indexOf(".")));
				}
		        for(PersonalTmp pt:list) {  
		        	logger.debug(ll.toString()+"===="+pt.getPaperNo());
		            if(!ll.contains(pt.getPaperNo())){  
						throw new ApplicationException(ErrorCode.FILE_IS_NULL, "photo  does not have personal.paperNo ["+pt.getPaperNo()+"] belong to batch["+pt.getApplyBatchNo()+"]");

		            }  
		        }  
		        return true;
			}else{
				return false;
			}
				
				

		
	}
	
	
	/**
	 * 按批次导入
	 * @param out
	 * @param no
	 * @return
	 * @throws ApplicationException 
	 */
	public static Map<String,String> batchUploadPhotosByApplyBatchNo(String root, String applyNo) throws ApplicationException{
		Map<String,String> map = new HashMap<>();
		String filePath=root+PathContants.PROJECT_PATH_IMG+File.separator+applyNo;  //该批次图片文件夹路径
		File f = new File(filePath);
		if(!f.exists()){
			f.mkdirs();
		}
		
		File[] lll = f.listFiles();
		if(lll.length==0){
			logger.info("----------------[{}]文件夹内无图片可导入----------------",filePath);
			throw new ApplicationException(
					ErrorCode.FILE_IS_NULL, "This File is null");
		}
		File fi = new File(root+PathContants.PROJECT_PATH_IMG_IMPORTED);
		if(!fi.exists()){
			fi.mkdirs();
		}
		List<String> ls = new ArrayList<>();
		for(File fff:lll){
			String s = fff.getName();
			if(s.endsWith(".jpg")||s.endsWith(".png")||s.endsWith(".bmp")||s.endsWith(".gif")){
				ls.add(s);
				String paperNo = s.substring(0, s.indexOf("."));
				String ppp = fi.getAbsolutePath()+File.separator+s;
				fff.renameTo(new File(ppp));
				
				map.put(paperNo, PathContants.PROJECT_PATH_IMG_IMPORTED+File.separator+s);
			}
		}
		
		f.delete();
		
		return map;
	}



	/**
	 * 单笔上传附件
	 * 
	 * @param request
	 * @return
	 * @throws ApplicationException 
	 */
	public static List<String> singleUploadCert(String root,String paperNo) throws ApplicationException {
		List<String> l = new ArrayList<>();
		String oo = "";
		String ppp = in_single_enclosure_Dir_Physics+File.separator+paperNo;
		if(HttpUtil.getResponseCode(ppp)==HttpContants.NOT_FOUND){
			throw new ApplicationException(
					ErrorCode.FILE_IS_NULL, "This File is null");
		}
		
		
		List<String> ls  = HtmlParseUtil.parseHtml(ppp);
		Iterator<String> it= ls.iterator();
		while(it.hasNext()){
			String certName= it.next();
			if(!certName.contains(".")){
				it.remove();
			}
		}
		if(ls.size()==0){
			throw new ApplicationException(
					ErrorCode.FILE_IS_NULL, "the Cert is null");
		}
		
		for(String certName:ls){
			oo = readImage(root, ppp+certName,PathContants.PROJECT_PATH_ENCLOSURE_IMPORTED);// 绝对路径
			l.add(oo);
		}
		
		
		return l;
	}


	/**
	 * 获取指定目录
	 * @return
	 * @throws ApplicationException 
	 */
	private static File[] getFileDir(String dir) throws ApplicationException{
		File fs = new File(dir);
		if (!fs.exists()) {
			System.out.println("mmp,這個不存在，还要自己创建");
			fs.mkdirs();
		}
		
		if (fs.isDirectory()) {
			File[] fileson = fs.listFiles();
			if (fileson.length == 0) {
				logger.warn("路径:{},[{}]文件夹是空的", fs.getAbsolutePath(),
						fs.getName());
				throw new ApplicationException(ErrorCode.FILE_IS_NULL,
						"This File is null");
			}
			return fileson;
		}else{
			throw new ApplicationException(ErrorCode.FILE_IS_NULL,
					"This File is null");
		}
	}
	
	/**
	 * 上传图片
	 * @param outpath
	 * @param photoName
	 * @param b
	 * @return
	 */
	 public static boolean uploadPhoto(String outpath,String photoName,byte[] b) {
		 boolean f=false;
		 File file = new File(outpath);
		 if(!file.exists()){
			 file.mkdirs();
		 }
		 try {
			OutputStream outputStream = new FileOutputStream(outpath+File.separator+photoName);
			outputStream.write(b);
			outputStream.flush();
			outputStream.close();
			File file2 = new File(outpath+File.separator+photoName);
			Image image=ImageIO.read(file2);
			BufferedImage buffImg=new  BufferedImage(72,80,BufferedImage.TYPE_INT_RGB);
			buffImg.getGraphics().drawImage(image.getScaledInstance(72, 80, Image.SCALE_SMOOTH), 0,0, null);
			ImageIO.write(buffImg, "PNG", new File(outpath+File.separator+photoName));
		} catch (IOException e) {
			e.printStackTrace();
			return f;
		}
		 f=true;
		 return f;
	 }
	 
	 /**
	  * 
	  * @param outpath /uploadImages/temp/img/applyNo
	  * 				/uploadImages/temp/excel/
	  * @param fileName
	  * @param input
	  * @return
	  */
	 public static boolean uploadTmpFile(String outpath,String fileName,InputStream input) {
		 boolean f=false;
		 File file = new File(outpath);
		 if(!file.exists()){
			 file.mkdirs();
			 logger.debug("上传路径【{}】",outpath);
		 }
		 try {
			OutputStream outputStream = new FileOutputStream(outpath+File.separator+fileName);
			int read = 0;
			byte[] byteArray = new byte[1024 * 1024 * 100];
			while ((read = input.read(byteArray)) != -1) {
				outputStream.write(byteArray, 0, read);
			}
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			
			return f;
		}
		 f=true;
		 return f;
	 }
	 
	 
	
	public static void main(String[] args) {
		// moveTotherFolders("D:\\resource\\unphotos\\1000_smk001\\111.jpg",
		// "D:\\resource\\photosed\\");
		System.out.println(new File("D:\\resource\\photosed\\").getName());
	}
}
